package com.cosmoplat.xikai.business.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cosmoplat.xikai.business.config.mes.MesUrl;
import com.cosmoplat.xikai.business.domain.BaseMaterial;
import com.cosmoplat.xikai.business.domain.mes.req.MesMaterialInitRequest;
import com.cosmoplat.xikai.business.domain.mes.req.MesRequest;
import com.cosmoplat.xikai.business.domain.mes.result.MesMaterialInitResult;
import com.cosmoplat.xikai.business.domain.mes.result.MesPageResult;
import com.cosmoplat.xikai.business.domain.mes.result.MesResult;
import com.cosmoplat.xikai.business.service.BaseMaterialService;
import com.cosmoplat.xikai.business.mapper.BaseMaterialMapper;
import com.cosmoplat.xikai.business.service.MesRequestService;
import com.cosmoplat.xikai.common.enums.DelFlagEnum;
import com.cosmoplat.xikai.common.exception.ServiceException;
import com.cosmoplat.xikai.common.utils.bean.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 22047582
 * @description 针对表【base_material】的数据库操作Service实现
 * @createDate 2025-01-07 13:51:30
 */
@Slf4j
@Service
public class BaseMaterialServiceImpl extends ServiceImpl<BaseMaterialMapper, BaseMaterial>
        implements BaseMaterialService {

    @Autowired
    private MesRequestService mesRequestService;

    @Autowired
    private MesUrl mesUrl;


    @Override
    public BaseMaterial getByMesMaterialId(String materialId) {
        LambdaQueryWrapper<BaseMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(BaseMaterial::getMaterialId, materialId)
                .eq(BaseMaterial::getIsDelete, DelFlagEnum.NORMAL.getCode());
        return getOne(queryWrapper);
    }

    @Override
    public boolean initMesData() {
        try {

            MesMaterialInitRequest req = new MesMaterialInitRequest();
            req.setPageIndex(1);
            req.setPageSize(100);
            MesRequest request = new MesRequest();
            request.setUrl(mesUrl.getMaterialInit());
            request.setJson(JSON.toJSONString(req));
            String res1 = mesRequestService.sendRequest(request);
            JSONObject jsonObject = JSONObject.parseObject(res1);
            MesResult<MesPageResult<MesMaterialInitResult>> result = jsonObject.toJavaObject(MesResult.class);
            if (result == null) {
                log.error("同步mes数据异常, 返回数据为空：{}", request);
            }
            if (!result.checkData()) {
                log.error("同步mes数据异常, 数据异常：{}", result);
                throw new ServiceException("同步mes数据异常, 数据异常");
            }
            MesPageResult<MesMaterialInitResult> pageResult = result.getData();
            List<MesMaterialInitResult> businessData = pageResult.getBusinessdata();
            if (CollectionUtils.isEmpty(businessData)) {
                log.error("同步mes数据异常, 返回数据businessdata为空：{}", result);
                return false;
            }

            int pageCount = pageResult.getPageCount();
            int total = 0;
            log.info("每页100个, 分页数量：{}", pageCount);
            for (int i = 1; i <= pageCount; i++) {
                req.setPageIndex(i);
                request.setJson(JSON.toJSONString(req));
                res1 = mesRequestService.sendRequest(request);
                jsonObject = JSONObject.parseObject(res1);
                result = jsonObject.toJavaObject(MesResult.class);
                if (result == null) {
                    log.error("同步mes数据异常, 返回数据为空：{}", request);
                }
                if (!result.checkData()) {
                    log.error("同步mes数据异常, 数据异常：{}", result);
                    throw new ServiceException("同步mes数据异常, 数据异常");
                }
                businessData = pageResult.getBusinessdata();
                if (CollectionUtils.isEmpty(businessData)) {
                    log.error("同步mes数据异常, 返回数据businessdata为空：{}", result);
                    return false;
                }
                List<BaseMaterial> materialList = new ArrayList<>(businessData.size());
                for (MesMaterialInitResult mesMaterialInitResult : businessData) {
                    BaseMaterial material = new BaseMaterial();
                    BeanUtils.copyProperties(mesMaterialInitResult, material);
                    material.setId(null);
                    material.setIsDelete(DelFlagEnum.NORMAL.getCode());
                    materialList.add(material);
                    total++;
                }
                saveBatch(materialList);
            }
            log.info("同步物料条数：{}", total);
            return true;

        } catch (Exception e) {
            log.error("同步mes数据异常：{}", e);
        }

        return false;
    }


}




